//
//  GTScrollView.m
//  GTSliderDemo
//
//  Created by yate1996 on 15/7/21.
//  Copyright (c) 2015年 yate1996. All rights reserved.
//
#define SCREENW [UIScreen mainScreen].bounds.size.width
#import "GTScrollView.h"
#import "VideoView.h"
#import "MBProgressHUD+MJ.h"
#import "HMVideoCell.h"
#import "HMVideo.h"
#import "LoadMoreCell.h"
#import "UIView+Extension.h"
#import <MediaPlayer/MediaPlayer.h>
@interface GTScrollView ()
//@property (nonatomic , strong)NSMutableArray *videosarray;
@end
@implementation GTScrollView

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        mNeedUseDelegate = YES;
        [self commInit];
    }
    return self;
}



-(void)commInit{
    if (_contentItems == nil) {
        _contentItems = [[NSMutableArray alloc] init];
    }
    if (_scrollView == nil) {
        _scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, self.frame.size.width, self.frame.size.height)];
        _scrollView.pagingEnabled = YES;
        _scrollView.delegate = self;
        _scrollView.bounces = NO;
        _scrollView.showsHorizontalScrollIndicator = NO;
        _scrollView.showsVerticalScrollIndicator = NO;
    }
    [self addSubview:_scrollView];
}
-(void)setupVideoDetail:(NSInteger)aNumerOfTables
{
//    for (int i = 0; i < aNumerOfTables; i++) {
    dispatch_queue_t mainQueue= dispatch_get_main_queue();
    dispatch_async(mainQueue, ^{
        NSString *urlStr = @"http://192.168.1.18:8080/MJServer/video";
        NSURL *url = [NSURL URLWithString:urlStr];
        NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url]; // GET
        request.timeoutInterval = 10;
        
        [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
            // 隐藏
            //        [MBProgressHUD hideHUD];
            if (data) {
                // 解析数据
                NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
                NSArray *array = dict[@"videos"];
                
                NSMutableArray *videos = [NSMutableArray array];
                for (NSDictionary *videoDict in array) {
                    HMVideo *video = [HMVideo videoWithDict:videoDict];
                    [videos addObject:video];
                }
                
//                [self.videosarray addObjectsFromArray: [videos copy]];
                [self.videoView.videos addObjectsFromArray:[videos copy]];
                // 刷新表格
                for(VideoView *videoView in self.contentItems){
                    [videoView reloadData];
                }
            } else {
                [MBProgressHUD showError:@"网络繁忙!!!"];
            }
        }];    });

//    }
}
//#pragma mark 添加ScrollowViewd的ContentView
-(void)setContentOfTables:(NSInteger)aNumerOfTables{
    [self setupVideoDetail:aNumerOfTables];
    for (int i = 0; i < aNumerOfTables; i++) {
        VideoView *videoView = [[VideoView alloc]initWithFrame:CGRectMake(SCREENW * i , 0, SCREENW, self.frame.size.height)];
        videoView.delegate = self;
        videoView.dataSource = self;
        videoView.showsVerticalScrollIndicator = NO;
        videoView.separatorStyle = UITableViewCellSeparatorStyleNone;
        self.videoView = videoView;
        LoadMoreCell *footView = [[[NSBundle mainBundle] loadNibNamed:@"LoadMoreCell" owner:self options:Nil] lastObject];
        footView.frame = CGRectMake(0, self.frame.size.height, 320, 64);
        self.videoView.tableFooterView = footView;
//        footView.hidden = YES;
        [_scrollView addSubview:videoView];
        [_contentItems addObject:videoView];
//        [self.videoView reloadData];
    }
    [_scrollView setContentSize:CGSizeMake(SCREENW * aNumerOfTables, self.frame.size.height)];
    for (VideoView *videoView in self.contentItems ) {
        [videoView reloadData];
    }
}

-(void)loadMoreData:(NSInteger)aNumerOfTables
{
    [self setupVideoDetail:aNumerOfTables];
}

#pragma mark 移动ScrollView到某个页面
-(void)moveScrollowViewAthIndex:(NSInteger)aIndex{
    mNeedUseDelegate = NO;
    CGRect vMoveRect = CGRectMake(self.frame.size.width * aIndex, 0, self.frame.size.width, self.frame.size.width);
    [_scrollView scrollRectToVisible:vMoveRect animated:YES];
    mCurrentPage= aIndex;
    if ([_delegate respondsToSelector:@selector(didScrollPageViewChangedPage:)]) {
        [_delegate didScrollPageViewChangedPage:mCurrentPage];
    }
}

#pragma mark - UIScrollViewDelegate
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
    mNeedUseDelegate = YES;
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    LoadMoreCell * footView = (LoadMoreCell *)self.videoView.tableFooterView;
    [footView.freshView stopAnimating];

    CGFloat offsetY = scrollView.contentOffset.y;
    
    // 当最后一个cell完全显示在眼前时，contentOffset的y值
    CGFloat judgeOffsetY = scrollView.contentSize.height + scrollView.contentInset.bottom - scrollView.height;
    NSLog(@"%f,%f",  judgeOffsetY,offsetY);
    if (offsetY >= judgeOffsetY) { // 最后一个cell完全进入视野范围内
        // 显示footer
        self.videoView.tableFooterView.hidden = NO;
            [self.videoView setContentOffset:CGPointMake(scrollView.contentOffset.x, judgeOffsetY - 50 - self.videoView.tableFooterView.height) animated:YES];
            [footView.freshView startAnimating];
            // 加载更多的微博数据
            [self performSelector:@selector(loadMoreData:) withObject:nil afterDelay:2.0];
    }
    
    int page = (_scrollView.contentOffset.x + SCREENW/2.0) / SCREENW;
    if (mCurrentPage == page) {
        return;
    }
    mCurrentPage = page;
    if ([_delegate respondsToSelector:@selector(didScrollPageViewChangedPage:)] && mNeedUseDelegate) {
        [_delegate didScrollPageViewChangedPage:mCurrentPage];
    }
}

#pragma mark TableViewDelegate代理方法

#pragma mark - 数据源
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [self.videoView.videos count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    HMVideoCell *cell = [HMVideoCell cellWithTableView:tableView];

    cell.video = self.videoView.videos[indexPath.row];
//    cell.video = self.videoView.videos[(NSInteger)arc4random_uniform((u_int32_t)[self.videoView.videos count])];
    
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 70;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    HMVideo *video = self.videoView.videos[indexPath.row];
    
    // 播放视频
    NSString *videoUrl = [NSString stringWithFormat:@"http://192.168.1.18:8080/MJServer/%@", video.url];
    
    //   NSString *videoUrl = [[NSBundle mainBundle] pathForResource:@"minion_01.mp4" ofType:nil];
    
    MPMoviePlayerViewController *playerVc = [[MPMoviePlayerViewController alloc] initWithContentURL:[NSURL URLWithString:videoUrl]];
    
    [[UIApplication sharedApplication].keyWindow.rootViewController presentMoviePlayerViewControllerAnimated:playerVc];
    
}

@end
